<?php

namespace common\logics;

use Yii;
use yii\helpers\Inflector;

/**
 * 基础面板数据模型
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class DashboardLogic extends \common\base\Model {

    /**
     * Token信息
     */
    private $_token = null;

    /**
     * 用户信息
     */
    private $_user = null;

    /**
     * 设置用户信息
     */
    public function setUser($data = null) {
        if (!$data) {
            if (!Yii::$app->user->isGuest) {
                $this->_user = Yii::$app->user->identity;
            }
        } else {
            $modelClass = Yii::$app->user->identityClass;
            if ($data instanceof $modelClass) {
                $this->_user = $data;
            } elseif (is_numeric($data)) {
                $this->_user = $modelClass::findOne($data);
            }
        }
    }

    /**
     * 获取用户信息
     */
    public function getUser() {
        return $this->_user;
    }

    /**
     * 获取用户信息
     */
    public function getUserId() {
        return $this->user ? $this->user->id : 0;
    }

    /**
     * 设置TOKEN信息
     */
    public function setToken($token) {
        $this->_token = $token;
        if ($token && $token->user) {
            $this->setUser($token->user);
        }
    }

    /**
     * 获取TOKEN信息
     */
    public function getToken() {
        return $this->_token;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        $attributes = $this->attributes;
        foreach ($attributes as $key => $vls) {
            if ($key == 'user') {
                $this->$key = $this->getUser();
                continue;
            }
            $method = 'set' . Inflector::camelize($key);
            $handler = array($this, $method);
            if ($this->hasMethod($method) && is_callable($handler)) {
                $this->$key = call_user_func_array($handler, [$vls]);
            }
        }
        return parent::fields();
    }

}
